package ru.evga.billboard.graph;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import ru.evga.billboard.editor.behaviors.EditorContext;
import ru.evga.billboard.graph.preference.GraphSettings;


public class Graph
{
    private Bus bus;
    private Background background;
    private FrameSet frameSet;
    private GraphSettings preference;
    
    public Graph(GraphSettings preference)
    {
        this.preference = preference;
        background = new Background(preference);
        bus = new Bus(preference);
        frameSet = new FrameSet(preference);
    }

    public void paint(Graphics2D g2, EditorContext context)
    {
        background.paint(g2, context);
        bus.paint(g2, context);
    }

    public Bus getBus()
    {
        return bus;
    }
    
    public Background getBackground()
    {
        return background;
    }

    public Rectangle2D getClipBounds(EditorContext context)
    {
        Rectangle2D bounds = bus.getBounds(context);
        bounds.add(background.getRectangle());
        return bounds;
    }

    public FrameSet getFrameSet()
    {
        return frameSet;
    }
    
    public GraphSettings getPreference()
    {
        return preference;
    }
    
    public void export(String fileName, boolean bin) throws IOException
    {
        File f = new File(fileName);
        FileOutputStream fos = new FileOutputStream(f);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        for (int frameNo = 0; frameNo < frameSet.getFrameCount(); frameNo++)
        {
            Frame frame = frameSet.getFrame(frameNo);
            List<Column> columns = bus.getColumns();
            int columnNo = 0;
            for (Column column : columns)
            {
                StringBuilder sb = new StringBuilder();
                List<Cross> crosses = column.getCrosses();
                int crossNo = 0;
                for (Cross cross : crosses)
                {
                    if (cross.isHasDiode() && frame.isOn(columnNo, crossNo))
                    {
                        sb.insert(0,"1");
                    }
                    else
                    {
                        sb.insert(0,"0");
                    }
                    crossNo++;
                }
                if (bin)
                {
                    bos.write(sb.toString().getBytes());
                }
                else
                {
                    Integer val = Integer.parseInt(sb.toString(), 2);
                    bos.write(Integer.toHexString(val).getBytes());
                }
                bos.write("\n".getBytes());
                columnNo++;
            }
        }
        
        bos.flush();
        bos.close();
    }
}
